module(..., package.seeall)
----------------------------------------------------------------------------------
--
-- scenetemplate.lua
--
----------------------------------------------------------------------------------

local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
local gui = require "Stage1.Stage1HomeGui".new()
-- require("movieclip")
local sfx = require "Stage1.sfx"
local ui = require ("ui")
local wEasing = require "wEasing"
system.activate( "multitouch" )
----------------------------------------------------------------------------------
-- 
--	NOTE:
--	
--	Code outside of listener functions (below) will only be executed once,
--	unless storyboard.removeScene() is called.
-- 
---------------------------------------------------------------------------------

---------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------

-- Called when the scene's view does not exist:
function scene:createScene( event )
	local group = self.view
	
------------------------------------------------------------
--- variableName
------------------------------------------------------------
	
	
end


-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
	local mainGroup = self.view
	
	local backgroundGroup, generateItemsGroup, buttonGroup
	
	local redFlag,yellowFlag,greenFlag = false,false,false
	local feetToTouch = {}
	local totalTimer = nil
	local eachTurnTimer = nil
	local timerText
	local isTouch1, isTouch2 = false, false
	local instance = {}
	local countDown = 2
	local score = 0
	local totalTime = 20100
	local timeEachTurn = 1 * 30
	local timeDelay = 100
	local xPrevious1,yPrevious1 = 0,0
	local xPrevious2,yPrevious2 = 0,0
	local redHammer,yellowHammer,greenHammer = nil, nil, nil
	local bg, pause, pauseButton
	local timeFormer,timeLater,timeDelta = 0,0,0
	local tempTime = 4
	local tempTimer
	local _gameOver
	local txtTime
	local i = 0
	local scoreMinus
	local scoreText,timerText
	local generateFirst
	local isWinTurn
	local turnTimer
	local countDownTime
	local tFormer
	local _score = {}
	
-----------------------------------------------------------------------------
------Function
-----------------------------------------------------------------------------
function init()
	_score = {42,44,46,48,50}
	tFormer = 0
	-- isWinTurn = false
	countDownTime = timeEachTurn
	scoreMinus = 0
	generateFirst = nil
	score = 0
	pauseButton.isVisible = true
	
	totalTime = 23600
	totalTimer = timer.performWithDelay(100,manageTotalTime,0)
end
function onTouch(event)
	local t = event.target
	local phase = event.phase
	if(phase == "began")then
		audio.play(sfx.clickSound)
		for k,v in pairs(instance)do
			if(t.id == v.id)then
				tFormer = totalTime
				countDown = countDown - 1
				score = score + 1
				scoreText.text = score
				scoreText.alpha = 1
				destroyWatch(v.x,v.y)
				display.remove(v)
				table.remove(instance,k)
				local _tempTime = 50
				local _tempTimer 
				_tempTimer = timer.performWithDelay(10,function()
									_tempTime = _tempTime - 10
									if(_tempTime < 0)then
										-- local temp = math.random(1,2)
										timer.cancel(_tempTimer)
										random1Position()
										tFormer = totalTime
										countDown = 1
										scoreMinus = 1
										timeCountDown = timeEachTurn
										-- if(checkWin())then
											-- tFormer = system.getTimer()
											-- isWinTurn = true
											-- if(temp == 1)then
												-- random1Position()
												-- countDown = 1
												-- scoreMinus = 1
											-- else
												-- random2Position()
												-- countDown = 2
												-- scoreMinus = 2
											-- end
											-- timeCountDown = timeEachTurn
										-- end
									end
								end,0)
				return
			end
		end
		if(scoreMinus > 0)then
			score = score - 1
			scoreMinus = scoreMinus - 1
		end
		scoreText.text = score
		scoreText.alpha = 1
	end
end

function checkWin()
	if(countDown <= 0)then
		return true
	else
		return false
	end
end
	
	---function to pause scene
onStartPopup = function()
	pauseButton:removeEventListener("tap",onStartPopup)
	if(tempTimer ~= nil)then
		timeFormer = system.getTimer()
		timer.pause(tempTimer)
	end
	if(totalTimer ~= nil)then
		timer.pause(totalTimer)
	end
	redHammer:removeEventListener("touch",onTouch)
	yellowHammer:removeEventListener("touch",onTouch)
	greenHammer:removeEventListener("touch",onTouch)
end
	
	--function to resume from popup
onResumeFromPopup = function()
	pauseButton:addEventListener("tap",onStartPopup)
	timeLater = system.getTimer()
	if(tempTimer ~= nil)then
		timer.resume(tempTimer)
	end
	if(totalTimer ~= nil)then
		totalTime = totalTime + 1
		timer.resume(totalTimer)
	end
	
	redHammer:addEventListener("touch",onTouch)
	yellowHammer:addEventListener("touch",onTouch)
	greenHammer:addEventListener("touch",onTouch)
	-- timeDelta = timeDelta + timeLater - timeFormer
end
	
function generateWatch(xCoordinate,yCoordinate)
	-- an image sheet with a watch
	local sheet1 = graphics.newImageSheet( gui.dancer.fn, { width=278, height=248, numFrames=2 } )

	-- play 2 frames every 250 ms
	local instance = display.newSprite( sheet1, { name = "watch", start=1, count=2, time=250 } )
	instance.x = xCoordinate
	if(xCoordinate == 50) then
		instance.id = "red"
	elseif(xCoordinate == 160) then
		instance.id = "yellow"
	else instance.id = "green"
	end
	----------random
	instance.y = yCoordinate
	instance.xScale = 0.6
	instance.yScale = 0.6
	instance:play()
	return instance
end
	
function destroyWatch(xCoordinate,yCoordinate)
	local timerDestroy = nil
	local instanceDestroy
	local function manageTimerDestroy(event)
		display.remove(instanceDestroy)
		timer.cancel(timerDestroy)
		
	end
	timerDestroy = timer.performWithDelay(200,manageTimerDestroy,1)
	
	instanceDestroy = display.newImageRect("Images/Stage1/crack.png",180,180)
	instanceDestroy.x = xCoordinate
	instanceDestroy.y = yCoordinate
end
	
function manageTotalTime()
	totalTime = totalTime - 100
	if(totalTime> 21000)then
		readyText.text = math.round((totalTime - 20500)/1000)
		readyText.alpha = 1
	elseif(totalTime <= 21000 and totalTime > 20000)then
		readyText.text = "Action"
	elseif(totalTime <= 20000 and totalTime >=0)then
		readyText.alpha = 0
		timerText.text = math.round(totalTime/100)/10
		timerText.alpha = 1
		if(generateFirst == nil)then
			tFormer = totalTime
			generateFirst = random1Position()
			scoreMinus = 1
			redHammer:addEventListener("touch",onTouch)
			yellowHammer:addEventListener("touch",onTouch)
			greenHammer:addEventListener("touch",onTouch)
			timeCountDown = timeEachTurn
			countDown = 1
		end
		if((tFormer - totalTime) >= 900)then
			redHammer:removeEventListener("touch",onTouch)
			greenHammer:removeEventListener("touch",onTouch)
			yellowHammer:removeEventListener("touch",onTouch)
		end
		if(tFormer ~= 0 and (tFormer - totalTime) >= 1000)then
			
			tFormer = totalTime
				for k,v in pairs(instance)do
					display.remove(v)
					table.remove(v)
					v = nil
					k = nil
				end
				score = score - scoreMinus
				scoreText.text = score
				scoreText.alpha = 1
				local _tempTime = 50
				local _tempTimer 
				_tempTimer = timer.performWithDelay(10,function()
									_tempTime = _tempTime - 10
									if(_tempTime < 0)then
										timer.cancel(_tempTimer)
										random1Position()
										redHammer:addEventListener("touch",onTouch)
										greenHammer:addEventListener("touch",onTouch)
										yellowHammer:addEventListener("touch",onTouch)
										countDown = 1
										scoreMinus = 1
										timeCountDown = timeEachTurn
										-- tFormer = system.getTimer()
									end
								end,0)
		end
		
	elseif(totalTime < 0)then
		timer.cancel(totalTimer)
		pauseButton.isVisible = false
		
		redHammer:removeEventListener("touch",onTouch)
		greenHammer:removeEventListener("touch",onTouch)
		yellowHammer:removeEventListener("touch",onTouch)
		for k,v in pairs(instance)do
			-- v:pause()
			display.remove(v)
			table.remove(instance,k)
		end
		-- Runtime:removeEventListener("enterFrame",onEnterFrame)
		if(tempTimer ~= nil)then
			timer.cancel(tempTimer)
		end
		if(_tempTimer ~= nil)then
			timer.cancel(_tempTimer)
		end
		finishedGame()
	end
end
	
function random1Position()
	local randomX = 50 + 110*(math.random(1,3) - 1)
	local randomY = 40 + math.random(1,3) * 80
	
	while ((randomX == xPrevious1 and randomY == yPrevious1) or (randomX == xPrevious2 and randomY == yPrevious2)) do
		randomX = 50 + 110*(math.random(1,3) - 1)
		randomY = 40 + math.random(1,3) * 80
	end
	redFlag = false
	yellowFlag = false
	greenFlag = false
	
	if(50 >= randomX) then
		redFlag = true
	elseif (50 < randomX and randomX <= 160) then
		yellowFlag = true
	elseif ( 160 < randomX and randomX <= 270) then
		greenFlag = true
	end
	xPrevious1 = randomX
	yPrevious1 = randomY
	xPrevious2 = randomX
	yPrevious2 = randomY
	instance[1] = generateWatch(randomX,randomY)
	generateItemsGroup:insert(instance[1])
	scoreText.alpha = 0
	-- isWinTurn = false
	return true
end
	
function random2Position()
	local randomX1 = 50;
	local randomX2 = 50;
	while(randomX1 == randomX2) do
		randomX1 = 50 + 110*(math.random(1,3) - 1)
		randomX2 = 50 + 110*(math.random(1,3) - 1)
	end

	local randomY1 = 40 + math.random(1,3) * 80
	local randomY2 = 40 + math.random(1,3) * 80
	
	while((randomX1 == xPrevious1 and randomY1 == yPrevious1) or (randomX1 == xPrevious2 and randomY1 == yPrevious2)
			or (randomX2 == xPrevious1 and randomY2 == yPrevious1) or (randomX2 == xPrevious2 and randomY2 == yPrevious2)) do
		randomY1 = 40 + math.random(1,3) * 80
		randomY2 = 40 + math.random(1,3) * 80
	end
	
	redFlag = false
	yellowFlag = false
	greenFlag = false
	
	if(50 >= randomX1) then
		redFlag = true
	elseif (50 < randomX1 and randomX1 <= 160) then
		yellowFlag = true
	elseif ( 160 < randomX1 and randomX1 <= 270) then
		greenFlag = true
	end
	
	if(50 >= randomX2) then
		redFlag = true
	elseif (50 < randomX2 and randomX2 <= 160) then
		yellowFlag = true
	elseif ( 160 < randomX2 and randomX2 <= 270) then
		greenFlag = true
	end
	
	xPrevious1 = randomX1
	yPrevious1 = randomY1
	xPrevious2 = randomX2
	yPrevious2 = randomY2
	
	instance[1] = generateWatch(randomX1,randomY1)
	instance[2] = generateWatch(randomX2,randomY2)
	generateItemsGroup:insert(instance[1])
	generateItemsGroup:insert(instance[2])
	scoreText.alpha = 0
	
	-- isWinTurn = false
	return true
end
	
function onReplayButtonTap()
	scoreText.alpha = 0
	for k,v in pairs(instance)do
		if(v.id ~= nil)then
		display.remove(v)
		table.remove(instance,k)
		v = nil
		k = nil
		end
	end
	if(totalTimer ~= nil)then
		timer.cancel(totalTimer)
	end
	if(tempTimer ~= nil)then
		timer.cancel(tempTimer)
	end
	if(_tempTimer ~= nil)then
		timer.cancel(_tempTimer)
	end
	timerText.alpha = 0
	scoreText.alpha = 0
	init()
end
	
function finishedGame()
	local temp = math.round((score - 42)/2)
	local g1
	if(temp < 0)then
		g1 = require "popup.popupWin".new(score,0,_score,onReplayButtonTap)
	else
		g1 = require "popup.popupWin".new(score,temp,_score,onReplayButtonTap)
	end
	transition.to(g1,{time = 200,alpha = 1, x = 0, y = 0, transition = wEasing.easeOutElastic})
end
	
-----------------------------------------------------------------------------
-- Background and genaral button, group
-----------------------------------------------------------------------------

backgroundGroup = display.newGroup()
generateItemsGroup = display.newGroup()
buttonGroup = display.newGroup()
mainGroup:insert(backgroundGroup)
mainGroup:insert(generateItemsGroup)
mainGroup:insert(buttonGroup)

-----------[[background]]------------------
bg = display.newImageRect(gui.bg.fn, gui.bg.width, gui.bg.height)
	bg.x = gui.bg.x
	bg.y = gui.bg.y
backgroundGroup:insert(bg)


-----[[pause button]]-----------------
pauseButton = ui.newButton({
	defaultSrc = gui.pauseButton.fn,
	overSrc = gui.pauseButton.fn,
	defaultX = gui.pauseButton.w,
	defaultY = gui.pauseButton.h,
	overX = gui.pauseButton.w*1.2,
	overY = gui.pauseButton.h*1.2,
	x = gui.pauseButton.x,
	y = gui.pauseButton.y,
	
	onRelease = function()
		local g2 = require "popup.popupPause".new(onResumeFromPopup,onReplayButtonTap)
		local group2 = display.newGroup()
		group2:insert(g2)
		mainGroup:insert(group2)
		group2.y = -300
		transition.to(group2,{time = 1000,alpha = 1, x = 0, y = 0, transition = wEasing.easeOutElastic, onStart = onStartPopup})
	end
})

pauseButton.isVisible = true
mainGroup:insert(pauseButton)

------------------------------------------------------------------------------
------------------------[[Button]]
-------------------------------------------------------------------------------

redHammer = display.newImageRect(gui.redHammer.fn, gui.redHammer.width, gui.redHammer.height)
	redHammer.x = gui.redHammer.x
	redHammer.y = gui.redHammer.y
	redHammer.id = "red"
backgroundGroup:insert(redHammer)

yellowHammer = display.newImageRect(gui.yellowHammer.fn, gui.yellowHammer.width, gui.yellowHammer.height)
	yellowHammer.x = gui.yellowHammer.x
	yellowHammer.y = gui.yellowHammer.y
	yellowHammer.id = "yellow"
backgroundGroup:insert(yellowHammer)

greenHammer = display.newImageRect(gui.greenHammer.fn, gui.greenHammer.width, gui.greenHammer.height)
	greenHammer.x = gui.greenHammer.x
	greenHammer.y = gui.greenHammer.y
	greenHammer.id = "green"
backgroundGroup:insert(greenHammer)

--------------------------------------------------------------------------
---------------------------- [[Timer]]
--------------------------------------------------------------------------

timerText = display.newText(gui.timer.text, gui.timer.left, gui.timer.top, gui.timer.font, gui.timer.fontSize)
	timerText:setTextColor(gui.timer.red, gui.timer.green, gui.timer.red, gui.timer.alpha) 
	timerText.x = gui.timer.x
	timerText.y = gui.timer.y
	timerText.alpha = 0
buttonGroup:insert(timerText)


-------------------------------------------------------------------------------------
----------------------------- Score
-------------------------------------------------------------------------------------

scoreText = display.newText(gui.score.text, gui.score.left, gui.score.top, gui.score.font, gui.score.fontSize)
	scoreText:setTextColor(gui.score.red, gui.score.green, gui.score.red, gui.score.alpha)
	scoreText.x = gui.score.x
	scoreText.y = gui.score.y
	scoreText.alpha = 0
buttonGroup:insert(scoreText)

readyText = display.newText(gui.ready.text, gui.ready.left, gui.ready.top, gui.ready.font, gui.ready.fontSize)
	readyText:setTextColor(unpack(gui.ready.color))
	readyText.x = gui.ready.x
	readyText.y = gui.ready.y
	readyText.alpha = 0
buttonGroup:insert(readyText)

replayButton = ui.newButton({
	defaultSrc = gui.replayButton.fn,
	overSrc = gui.replayButton.fn,
	defaultX = gui.replayButton.w,
	defaultY = gui.replayButton.h,
	overX = gui.replayButton.w,
	overY = gui.replayButton.h,
	x = gui.replayButton.x,
	y = gui.replayButton.y,
	
	onRelease = onReplayButtonTap
})
buttonGroup:insert(replayButton)
	
_gameOver = display.newText(buttonGroup,"GAME OVER", gui.score.x, gui.score.y, gui.score.font, gui.score.fontSize)
	_gameOver.x = display.contentCenterX
	_gameOver.y = display.contentCenterY
	_gameOver:setTextColor(unpack(gui.score.color))
	_gameOver.alpha = 0
--------------------------------------------------------
----------------generate first watch
--------------------------------------------------------


init()
-----------------------------------------------------------
--------------------listener
----------------------------------------------------------



	-----------------------------------------------------------------------------
	
end


-- Called when scene is about to move offscreen:
function scene:exitScene( event )
	local group = self.view
	
	-----------------------------------------------------------------------------
	
	--	INSERT code here (e.g. stop timers, remove listeners, unload sounds, etc.)
	
	-----------------------------------------------------------------------------
	
end


-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
	local group = self.view
	
	-----------------------------------------------------------------------------
	
	--	INSERT code here (e.g. remove listeners, widgets, save state, etc.)
	
	-----------------------------------------------------------------------------
	
end

---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------

-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )

-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )

-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )

-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )

---------------------------------------------------------------------------------

return scene
